var express = require('express');
var router = express.Router();
var sql = require('./../sql/index')
var cart = require('./../sql/cart')
var uuid = require('node-uuid')
var Kind = require('./../sql/kind');

/**
 * @api {post} /api/cart/add 加入购物车
 * @apiDescription 加入购物车
 * @apiName /api/cart/add
 * @apiGroup cart
 * @apiParam {string} token token
 * @apiParam {string} usersid 用户id
 * @apiParam {string} kindid 产品id
 * @apiParam {number} num 加入购物车的数量
 * @apiSuccess {json} data
 * @apiSuccessExample {json} Success-Response:
 *{
 *   code: '10088',
 *   message: '加入购物车成功'
 *      }
 * {
     code:'10089',
     message:"token值失效"
         }
 * @apiSampleRequest http://localhost:3000/api/cart/add
 * @apiVersion 1.0.0
 */

router.post('/add', (req, res, next) => {
    // 检查用户是否登录，登录了才可以加入购物车，没有则不行
    // sms.validateToken(req, res, next).then(() => {
        //res.send(req.body)
        
        let { userid, kindid, num } = req.body;
        console.log(userid)
        num = num * 1 || 1;
        // 去数据库中查询，如果存在就修改并更新数据库，如果没有这个商品那么就直接插入
        sql.find(cart, { userid, kindid }, { _id: 0 }).then(data => {
            if (data.length > 0) {
                sql.update(cart, { userid, kindid }, { $inc: { num: num } }).then(() => {
                    res.send({
                        code: '10088',
                        message: "加入购物车成功"
                    });
                })
            } else {
                Kind.find({ 'data.kindid': { $eq: `${kindid}` } },{'data':{$elemMatch:{'kindid':`${kindid}`}}}).then(da => {
                       sql.insert(cart, {
                           cartid: 'cartid_' + uuid.v1(),
                           userid,
                           kindid,
                           data: da[0].data[0],
                           num
                       }).then(() => {
                           res.send({
                               code: '10088',
                               message: "加入购物车成功"
                           })
              })
                })
            }
            // 失败了就说明token值没有或者已经过期
        })
    // }).catch(() => {
    //     res.send({
    //         code: '10089',
    //         message: "token值失效"
    //     })
    // })
})

/**
 * @api {get} /api/cart 购物车数据接口
 * @apiDescription 购物车数据
 * @apiName /api/cart
 * @apiGroup cart
 * @apiParam {string} token token
 * @apiParam {string} usersid 用户id
 * @apiSuccess {json} data
 * @apiSuccessExample {json} Success-Response:
 *{
 *   code: '10031',
 *   message: '购物车的数据'
 *   data:{}
 *     }
 * {
     code:'10030',
     message:"购物车空空如吔"
         }
    {
     code:'10032',
     message:"token值无效"
         }
 * @apiSampleRequest http://localhost:2100/api/cart
 * @apiVersion 1.0.0
 */

router.get('/', (req, res, next) => {  
        let { usersid } = req.query;
        let arr = [];
        sql.find(cart, { usersid }, { _id: 0 }).then(data => {
            if (data.length === 0) {
                res.send({
                    code: '10030',
                    messsge: '购物车空空如也'
                })
            } else {  
                res.send({
                    code: '10031',
                    message: '购物车的数据',
                    data:data
                    // data2:arr
                })   
        }
     })
})



/**
 * @api {post} /api/cart/update 修改产品数量接口
 * @apiDescription 修改产品数量
 * @apiName /api/cart/update
 * @apiGroup cart
 * @apiParam {string} token token
 * @apiParam {string} cartid 购物车id
 * @apiParam {number} num 修改产品的数量
 * @apiSuccess {json} data
 * @apiSuccessExample {json} Success-Response:
 *{
 *   code: '10090',
 *   message: '加入购物车成功'
 *      }
 * {
     code:'10091',
     message:"token值失效"
         }
 * @apiSampleRequest http://localhost:2100/api/cart/update
 * @apiVersion 1.0.0
 */

router.post('/update', (req, res, next) => {
    // 检查用户是否登录，登录了才可以加入购物车，没有则不行
    sms.validateToken(req, res, next).then(() => {
        let { cartid, num } = req.body;
        num = num * 1 || 1;
        sql.update(cart, {cartid},{$set: {num: num}}).then(()=>{
            res.send({
                code: '10090',
                message: "修改成功"
            })
        })
    }).catch(() => {
        res.send({
            code: '10091',
            message: "token值失效"
        })
    })
})

/**
 * @api {get} /api/cart/datale 删除产品数量接口
 * @apiDescription 删除产品数量
 * @apiName /api/cart/datale
 * @apiGroup cart
 * @apiParam {string} token token
 * @apiParam {string} cartid 购物车id
 * @apiSuccess {json} data
 * @apiSuccessExample {json} Success-Response:
 *{
 *   code: '10092',
 *   message: '删除成功'
 *      }
 * {
     code:'10093',
     message:"token值失效"
         }
 * @apiSampleRequest http://localhost:2100/api/cart/datale
 * @apiVersion 1.0.0
 */

router.get('/delete', (req, res, next) => {
    // 检查用户是否登录，登录了才可以加入购物车，没有则不行
    sms.validateToken(req, res, next).then(() => {
        let { cartid } = req.query;
        sql.delete(cart, {cartid}).then(()=>{
            res.send({
                code: '10092',
                message: "删除成功"
            })
        })
    }).catch(() => {
        res.send({
            code: '10093',
            message: "token值失效"
        })
    })
})

module.exports = router;


